package com.fmdj.mis.api.controller;

import cn.hutool.core.bean.BeanUtil;
import com.fmdj.common.util.CommonResult;
import com.fmdj.common.util.PageUtils;
import com.fmdj.mis.api.controller.form.*;
import com.fmdj.mis.api.db.pojo.DeptEntity;
import com.fmdj.mis.api.service.DeptService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/dept")
@Tag(name = "DeptController", description = "部门Web接口")
@Slf4j
public class DeptController {

    @Autowired
    private DeptService deptService;

    @PostMapping("/selectDeptByPage")
    @Operation(summary = "分页查询部门")
    public CommonResult selectDeptByPage(@RequestBody @Valid SearchDeptByPageForm form) {
        Map<String, Object> map = BeanUtil.beanToMap(form);
        PageUtils pageUtils = deptService.searchDeptByPage(map);
        return CommonResult.ok().put(CommonResult.RETURN_PAGE, pageUtils);
    }

    @GetMapping("/selectAllDept")
    @Operation(summary = "查询所有部门")
    public CommonResult selectAllDept() {
        ArrayList<HashMap> list = deptService.searchAllDept();
        return CommonResult.ok().put("list", list);
    }

    @PostMapping("/selectById")
    @Operation(summary = "根据id查询部门")
    public CommonResult selectById(@RequestBody @Valid SearchDeptByIdForm form) {
        HashMap hashMap = deptService.searchById(form.getId());
        return CommonResult.ok(hashMap);
    }

    @PostMapping("/insert")
    @Operation(summary = "新增部门")
    public CommonResult insert(@RequestBody @Valid InsertDeptForm form) {
        DeptEntity dept = new DeptEntity();

        dept.setDeptName(form.getDeptName());
        dept.setTel(form.getTel());
        dept.setEmail(form.getEmail());
        dept.setDesc(form.getDesc());

        int rows = deptService.insert(dept);

        return CommonResult.ok().put(CommonResult.RETURN_ROW, rows);
    }

    @PostMapping("/update")
    @Operation(summary = "更新部门")
    public CommonResult update(@RequestBody @Valid UpdateDeptForm form) {
        DeptEntity dept = new DeptEntity();

        dept.setId(form.getId());
        dept.setDeptName(form.getDeptName());
        dept.setTel(form.getTel());
        dept.setEmail(form.getEmail());
        dept.setDesc(form.getDesc());

        int rows = deptService.update(dept);

        return CommonResult.ok().put(CommonResult.RETURN_ROW, rows);
    }

    @PostMapping("/deleteDeptByIds")
    @Operation(summary = "删除部门")
    public CommonResult delete(@RequestBody @Valid DeleteDeptByIdsForm form) {
        int rows = deptService.deleteDeptByIds(form.getIds());
        return CommonResult.ok().put(CommonResult.RETURN_ROW, rows);
    }
}
